const express = require('express');
const router = express.Router();
const { Banner } = require('../models');
const { success, fail } = require('../utils/response');

// 获取列表（带分页和筛选）
const { Op } = require('sequelize');

router.post('/list', async (req, res) => {
    const {
        page = 1,
        pageSize = 10,
        keyword,
        isActive
    } = req.body;

    const offset = (page - 1) * pageSize;

    // 基础条件：未假删
    const where = {
        status: 1,
    };

    // 模糊搜索关键词匹配 title、linkUrl、position、remark 任意字段
    if (keyword) {
        where[Op.or] = [
            { title: { [Op.like]: `%${keyword}%` } },
            { linkUrl: { [Op.like]: `%${keyword}%` } },
            { position: { [Op.like]: `%${keyword}%` } },
            { remark: { [Op.like]: `%${keyword}%` } }
        ];
    }

    if (isActive !== 3) {
        where.isActive = isActive;
    }

    try {
        const { count, rows } = await Banner.findAndCountAll({
            where,
            limit: Number(pageSize),
            offset: Number(offset),
            order: [['sortOrder', 'ASC'], ['createdAt', 'DESC']],
        });

        return success(res, '', { total: count, list: rows });
    } catch (err) {
        console.error('[banner] 列表失败:', err);
        return fail(res, '获取失败');
    }
});


// 新增
router.post('/create', async (req, res) => {
    try {
        const banner = await Banner.create(req.body);
        return success(res, '添加成功', banner);
    } catch (err) {
        console.error('[banner] 添加失败:', err);
        return fail(res, '添加失败');
    }
});

// 编辑或状态更新
router.post('/update', async (req, res) => {
    const { id, ...updateData } = req.body;

    if (!id) {
        return fail(res, '缺少 Banner ID');
    }

    // 检查是否有可更新的字段
    if (Object.keys(updateData).length === 0) {
        return fail(res, '没有提供要更新的字段');
    }

    try {
        const [affectedRows] = await Banner.update(updateData, { where: { id } });

        if (affectedRows === 0) {
            return fail(res, '未找到对应的 Banner 或无更新内容');
        }

        return success(res, '更新成功');
    } catch (err) {
        console.error('[banner] 更新失败:', err);
        return fail(res, '更新失败');
    }
});


// 假删除 Banner（支持单个或多个 ID）
router.post('/delete', async (req, res) => {
    let { ids } = req.body;

    if (!ids || (Array.isArray(ids) && ids.length === 0)) {
        return fail(res, '缺少要删除的 ID');
    }

    // 如果是单个 id，转成数组
    if (!Array.isArray(ids)) {
        ids = [ids];
    }

    try {
        const [affectedRows] = await Banner.update(
            { status: 0 }, // 假删除
            { where: { id: ids } }
        );

        if (affectedRows === 0) {
            return fail(res, '未找到对应的 Banner');
        }

        return success(res, `成功删除 ${affectedRows} 个 Banner`);
    } catch (err) {
        console.error('[banner] 删除失败:', err);
        return fail(res, '删除失败');
    }
});

module.exports = router;
